    var URL = 'http://127.0.0.1/api';
    var products = [];
    var zoneAll = [];
    var oWidth = window.screen.width;
    let array = [];
    let defaultArray = [];
    let prev;
    let after;
    function initLoading(){
        $("body").append("<!-- loading -->" +
            "<div class='modal fade' id='loading' tabindex='-1' role='dialog' aria-labelledby='myModalLabel' data-backdrop='static'>" +
            "<div class='modal-dialog' role='document'>" +
            "<div class='modal-content'>" +
            "<div class='modal-header'>" +
            "<h4 class='modal-title' id='myModalLabel'>提示</h4>" +
            "</div>" +
            "<div id='loadingText' class='modal-body'>" +
            "<span class='glyphicon glyphicon-refresh' aria-hidden='true'>1</span>" +
            "处理中，请稍候。。。" +
            "</div>" +
            "</div>" +
            "</div>" +
            "</div>"
        );
    }
    function showLoading(text){
        $("#loadingText").html(text);
        $("#loading").modal("show");
    }
    function hideLoading(){
        $("#loading").modal("hide");
    }
    function unique(arr) {
        let obj = {}
        return arr.filter((item, index) => {
            // 防止key重复
            let newItem = item + JSON.stringify(item)
            return obj.hasOwnProperty(newItem) ? false : obj[newItem] = true
        })
    }
    function compare(property){
        return function(a,b){
            var value1 = a[property];
            var value2 = b[property];
            return value1 - value2;
        }
    }

    Date.prototype.format = function(format){
        var o = {
            "M+" : this.getMonth()+1, //month
            "d+" : this.getDate(), //day
            "H+" : this.getHours(), //hour
            "m+" : this.getMinutes(), //minute
            "s+" : this.getSeconds(), //second
            "q+" : Math.floor((this.getMonth()+3)/3), //quarter
            "S" : this.getMilliseconds() //millisecond
        }

        if(/(y+)/.test(format)) {
            format = format.replace(RegExp.$1, (this.getFullYear()+"").substr(4 - RegExp.$1.length));
        }

        for(var k in o) {
            if(new RegExp("("+ k +")").test(format)) {
                format = format.replace(RegExp.$1, RegExp.$1.length==1 ? o[k] : ("00"+ o[k]).substr((""+ o[k]).length));
            }
        }
        return format;
    };

    function groupArr(list, field) {
        var obj = {};
        for (var i = 0; i < list.length; i++) {
            for (item in list[i]) {
                if (item == field) {
                    obj[list[i][item]] = {
                        list: obj[list[i][field]] ? obj[list[i][field]].list : [],
                        vc_zone_name: list[i].vc_zone_name
                    };
                }
            }
            obj[list[i][field]].list.push(list[i])
        }
        var att = [];
        for (item in obj) {
            att.push({
                list: obj[item].list,
                vc_zone_name: obj[item].vc_zone_name,
            })
        }
        return att;
    }

    function toUtf8(str) {
        var out, i, len, c;
        out = "";
        len = str.length;
        for (i = 0; i < len; i++) {
            c = str.charCodeAt(i);
            if ((c >= 0x0001) && (c <= 0x007F)) {
                out += str.charAt(i);
            } else if (c > 0x07FF) {
                out += String.fromCharCode(0xE0 | ((c >> 12) & 0x0F));
                out += String.fromCharCode(0x80 | ((c >> 6) & 0x3F));
                out += String.fromCharCode(0x80 | ((c >> 0) & 0x3F));
            } else {
                out += String.fromCharCode(0xC0 | ((c >> 6) & 0x1F));
                out += String.fromCharCode(0x80 | ((c >> 0) & 0x3F));
            }
        }
        return out;
    }
    function getQueryVariable(variable){
        var query = window.location.search.substring(1);
        var vars = query.split("&");
        for (var i=0;i<vars.length;i++) {
            var pair = vars[i].split("=");
            if(pair[0] == variable){return pair[1];}
        }
        return(false);
    }
    function isContainer(aa,bb){
        for(var i=0;i<bb.length;i++){
            if($.inArray(bb[i],aa)==-1){
                return false;
            }
        }
        return true;
    }
    //根据provider获取上网区域
    function getZoneList(provider,esim) {
        if(provider==0){
            $('#loading').modal('hide');
            $('.zone_items').empty();
            $('.tab-product>ul').empty();
            $('.tab-product .tab-content').empty();
            $('#buyButton').attr('disabled', true);
            $('#buyButton').css('background', '#ddd');
            $("#message-content").text("资源参数有问题");
            $("#myModal").modal();
            return;
        }
        $.ajax({
            type: "GET",
            contentType: "application/json;charset=UTF-8",
            headers: {
                'content-type': 'application/json'
            },
            url: URL+'/recharge',
            timeout: 60000,
            data: {action: 'query_product', provider: provider, esim:esim },
            success: function (res) {
                products = res.items;
                zoneAll = res.zones_list;
                let number = [1];
                let filterArr = zoneAll.filter(item=>{
                    return number.includes(item.ti_hot_zone)
                });
                var zoneList = filterArr;
                if (!products) {
                    return;
                }
                zoneFun(zoneList,esim,products);
            },
            error: function (res) {
                if (!res) {
                    $("#message-content").text("数据异常");
                    $("#myModal").modal();
                }
            }
        });
    }

    function selectProduct(arr,esim) {
        var map = {},
            dest = [];
        for (var i = 0; i < arr.length; i++) {
            var ai = arr[i];
            if (!map[ai.i_valid_days]) {
                dest.push({
                    title: ai.i_valid_days + "天包",
                    products: [ai],
                    i_valid_days: ai.i_valid_days
                });
                map[ai.i_valid_days] = ai;
            } else {
                for (var j = 0; j < dest.length; j++) {
                    var dj = dest[j];
                    if (dj.i_valid_days == ai.i_valid_days) {
                        dj.products.push(ai);
                        break;
                    }
                }
            }
        }
        // console.log(dest);
        var dString = '';
        var content = '';
        $('.tab-product .tab-content').children().remove();
        dest = dest.sort(compare('i_valid_days'));
        for (var n = 0; n < dest.length; n++) {
            var cc = '#day' + n;
            if (n == 0) {
                dString += '<li class="active"><a href=' + cc + '>' + dest[n].title + '</a></li>';
                content += '<div class="tab-pane active" id=day' + n + '><ul>';
            } else {
                dString += '<li><a href=' + cc + '>' + dest[n].title + '</a></li>';
                content += '<div class="tab-pane" id=day' + n + '><ul>';
            }
            for (var m = 0; m < dest[n].products.length; m++) {

                content += '<li class="product-list">' +
                    '<input class="radio_type" type="radio" value=' + dest[n].products[m].i_product_id + ' name="type"/>' +
                    '<input name="provider_type" type="hidden" value='+ dest[n].products[m].vc_provider_list+'>'+
                    '<input name="zones_str" type="hidden" value='+ dest[n].products[m].product_zones+'>'+
                    '<label class="product-name">' + dest[n].products[m].vc_name + '</label>';
                if(esim){
                    content += '<label class="product-price">' + dest[n].products[m].f_esim_selling_price + '</label></li>';
                } else {
                    content += '<label class="product-price">' + dest[n].products[m].f_top_up_price + '</label></li>';
                }
            }
            content += '</ul></div>';
            if(dest[n].products.length>1){
                $('.dropdown').css('display','block')
            }
        }
        // console.log(dString);
        $('#myTab').children().remove();
        $('#myTab').append(dString);
        $('.tab-product .tab-content').append(content);
        $('.tab-content .active .product-list').each(function (index) {
            array[index] = $(this);
            defaultArray[index] = $(this);
        });
        // if(array.length>1){
        //     $('.dropdown').css('display','block');
        // } else {
        //     $('.dropdown').css('display','none');
        // }
        // console.log(array);
        $('.package-select').css('display', 'block');
        $('#buyButton').attr('disabled', false);
        $('#buyButton').css('background', '#FF6A00');
        $(function () {
            $('#myTab a:first').tab('show');
        });
        $('#myTab a').click(function (e) {
            e.preventDefault();
            $(this).tab('show');
        });
        $('.product-list').click(function (e) {
            $('.product-list').children('.radio_type').prop('checked', false);
            $(this).children('.radio_type').prop('checked', true);
            if(esim==0){
                rechargeByBuy();
            } else if(esim==1) {
                productByBuy();
            }
        });
        if (oWidth <= 320) {
            $('.product-list .product-name').css({
                "width":'140px',
                "word-wrap": "break-word !important",
                "word-break": "normal !important",
                "white-space": "unset",
                "line-height":'unset'
            });
        }else if(oWidth <= 375 && oWidth>320){
            $('.product-list .product-name').css({"width":'200px'});
        }else if(oWidth>375){
            $('.product-list .product-name').css({"min-width":'200px'});
        }
    }

    function ServerQueryAccount(account) {
        $('#loading').modal('show');
        $.ajax({
            type: "GET",
            contentType: "application/json;charset=UTF-8",
            headers: {
                'content-type': 'application/json'
            },
            url: URL+'/recharge',
            timeout: 60000,
            data: {action: 'query_account', keyword: account},
            success: function (res) {
                if(res.code==400 ||  res.message =="Invalid keyword parameter"){
                    $('#loading').modal('hide');
                    $("#message-content").text("卡号不正确");
                    $('.product-list-no').css('display','block');
                    $('.package-select').css('display', 'none');
                    $('.zone-recharge').css('display', 'none');
                    $("#myModal").modal();
                    return;
                }

                var arr = res.item;
                if (!arr){
                    $('.zone_items').empty();
                    $('.tab-product>ul').empty();
                    $('.tab-product .tab-content').empty();
                    $('#loading').modal('hide');
                    if($('.tab-product .tab-content').children().length==0){
                        $('#buyButton').css('background','#ddd');
                        $('#buyButton').attr('disabled','disabled');
                    }
                    $("#message-content").text("该卡暂不支持充值");
                    $('.package-select').css('display', 'none');
                    $('.zone-recharge').css('display', 'none');
                    $("#myModal").modal();
                    return;
                }
                if (!arr.dataPackage) {
                    $('.zone_items').empty();
                    $('.tab-product>ul').empty();
                    $('.tab-product').empty();
                    $('#loading').modal('hide');
                    $("#message-content").text("无套餐信息");
                    $('.package-select').css('display', 'none');
                    $('.zone-recharge').css('display', 'none');
                    $("#myModal").modal();
                    $('#buyButton').css('disabled',true);
                    return;
                }
                $('.zone-recharge').css('display','block');
                // var productName = arr.dataPackage ? arr.dataPackage[0].productName : '';
                // var lastName = '';
                // if (productName) {
                //     var search = "每天";
                //     var end = productName.indexOf(search);//获得字符串的开始位置
                //     if (end != -1) {
                //         lastName = productName.substring(0, end);//截取字符串
                //     } else {
                //         lastName = productName;
                //     }
                // }
                // $('.package-title').text(lastName);
                var status = $('.form-status-content .status');
                switch (arr.accountStatus) {
                    case 0:
                        status.text('未激活');
                        status.css({color: 'red'});
                        break;
                    case 1:
                        status.text('已激活');
                        status.css({color: 'green'});
                        break;
                    case 2:
                        status.text('已关闭');
                        status.css({color: 'red'});
                        break;
                    case 3:
                        status.text('已过期');
                        status.css({color: 'red'});
                        break;
                    case 4:
                        status.text('已销户');
                        status.css({color: 'red'});
                        break;
                    default:
                        break;
                }

                if(arr.bindImsi && arr.bindImsi.length>0) {
                    $("input[name='imsi']").attr('value',arr.bindImsi[0].imsi);
                } else {
                    $("input[name='imsi']").attr('value','');
                }
                getZoneList(arr.currentImsiProviderId,0);
                $('#loading').modal('hide');

            },
            //请求失败，包含具体的错误信息
            error: function (res) {
                $('#loading').modal('hide');
                if (!res) {
                    $("#message-content").text("数据异常");
                    $("#myModal").modal();
                } else {
                    var message = res.data.message;
                    var noticeContent = '';
                    if (message == 'Invalid keyword parameter') {
                        noticeContent = '查询条件不正确';
                    } else {
                        noticeContent = message;
                    }
                    $("#message-content").text(noticeContent);
                    $("#myModal").modal();
                }

            }
        });
    }

    function zoneFun(zoneList,esim,products) {
        $('.zone_items').children().remove();
        var Names = [];
        for (var j = 0; j < zoneList.length; j++) {
            var object = new Object();
            object.id = zoneList[j].i_zone_id;
            object.name = zoneList[j].vc_name;
            Names[j] = object;
        }
        //zone去重
        for (var i = 0; i < Names.length - 1; i++) {
            for (var j = Names.length - 1; j > 0; j--) {
                if (i != j) {
                    if (Names[i].name == Names[j].name) {
                        Names.splice(j, 1);
                    }
                }
            }
        }
        if (Names.length > 0) {
            var html = '';
            for (var i = 0; i < Names.length; i++) {
                html += '<label class=" zone_item"  v="' + Names[i].id + '" >' + Names[i].name + '</label>';
            }

            $('.zone_items').append(html);
            $('.zone-select').css('display', 'block');
            $('.package-select').css('display', 'none');
            $(".zone_items .zone_item").click(function () {
                $('#alert').fadeOut();
                if ($(this).hasClass("active")) {
                    $(this).removeClass("active").addClass("zone_item");
                } else {
                    $(this).removeClass("zone_item").addClass("active zone_item");
                    $('.tab-content .active .product-list').each(function (index) {
                        array[index] = $(this);
                        defaultArray[index] = $(this);
                    });
                }

                var chooseProduct = [];

                var zone_arr = [];
                if($(".zone_items .active").length==0){
                    $('.package-select').css('display', 'none');
                } else {
                    $('.package-select').css('display', 'block');
                    $(".zone_items .active").each(function () {
                        var select_zone = $(this).attr('v');
                        zone_arr.push(select_zone);
                    });
                    for (item in products) {
                        var vc_zone_ids = products[item].vc_zone_id.split(",");
                        var res = isContainer(vc_zone_ids,zone_arr);
                        if(res){
                            chooseProduct.push(products[item]);
                        }
                    }
                    chooseProduct = unique(chooseProduct);
                    // console.log(chooseProduct);
                    selectProduct(chooseProduct,esim);
                }
            });
            var notice = '';
            if(esim==1){
                notice = '<p style="padding-top: 10px;">请在上方选择要出行国家，支持多选！</p><p>购买eSIM产品前，请确保手机支持eSIM功能</p><p style="padding-bottom: 10px;"><a href="'+URL+'/supportModel">查看是否支持</a></p>'
            } else {
                notice = '请在上方选择要出行国家，支持多选！';
            }
            $('#alert').html('<div style="text-align: center;color:red;margin: 0 auto;width: 320px;">'+notice+'</div>').addClass('alert-warning').show();
        } else {
            $('#buyButton').attr('disabled', true);
            $('#buyButton').css('background', '#ddd');
            $("#message-content").text("暂无区域信息");
            $("#myModal").modal();
        }
    }




